package android.demo.engine;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.demo.engine.tasks.ServiceTask;
import android.demo.engine.tasks.Task;

public class PendingTaskManager implements ServiceCompletionListener {

	private Map<Integer,List<Task>> pendingTasks;
	private BusinessProcess mProcess;
	
	public PendingTaskManager(BusinessProcess process) {
		this.mProcess=process;
		this.pendingTasks=new HashMap<Integer, List<Task>>();
	}
	
	public void addTask(Task toWait,Task pending){
		getList(toWait.getId()).add(pending);
	}
	
	private List<Task> getList(int id) {
		List<Task> list = pendingTasks.get(id);
		if(list==null){
			list= new ArrayList<Task>();
			pendingTasks.put(id, list);
		}
		return list; 
	}
	public boolean hasPendingTasks(){
		return pendingTasks.values().isEmpty();
	}

	@Override
	public void onServiceCompletion(ServiceTask task) {
		task.removeListener(this);
		int completedTaskId=task.getId();
		List<Task> list= pendingTasks.get(completedTaskId);
		if(list!=null){
			pendingTasks.remove(completedTaskId);	
			for(Task t : list)
				mProcess.execTask(t);
		}		
	}
}
